﻿using System;
using System.Collections.Generic;
using System.Text;
//
using System.Data;
using System.Data.OleDb;
using System.Windows.Forms;
using System.Diagnostics;
using EncryptProject;
using RegistryLib;
using DBLib;
using SoftKeyLib;
using CommonBase;
using CommonClass;

namespace SurveillanceLib
{
    /// <summary>
    /// 数据操作类，公共业务逻辑层
    /// </summary>
    public class SurveillanceDAL : DataOperation
    {
        #region 常量

        // TreeNode
        public const string QUERY_GET_TREENODEDATA_BYSTATUS = "select * from TreeNode where Status = {0}"; // Tree 加载
        public const string QUERY_GET_TREENODEDATA = @"select ID, ParentID, TreeName, TreeText, DriverName, DriverPwd, DriverPort, ExceptChannel, 
switch(DriverType = 'DH', '大华', DriverType = 'HK', '海康', true, '其它') as DriverType, 
iif(Status = 1, '启用', '未启用') as Status
from TreeNode where ParentID <> '0' order by ID desc"; // Table 加载
        public const string QUERY_GET_ALLTREENODEDATA = "select * from TreeNode where ParentID <> '0' order by ID desc"; // 新增时
        public const string QUERY_GET_TREENODEDATA_BYID = "select * from TreeNode where ID = {0}"; // 修改时
        public const string QUERY_DELETE_TREENODE_BYID = "delete from TreeNode where ID = {0}"; // 删除时


        // SystemInformation
        public const string SYSTEM_GUID = "FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF";
        public const string QUERY_GET_ALLSYSTEMDATA_BYID = "select * from SystemInformation where ID = '{0}'"; // 查询时，修改时

        //////////////////////////////////////////////////////////////////////////

        // UserInformation
        public const string QUERY_GET_ALLUSERDATA = "select * from UserInformation"; // 查询时


        // ResetInformation
        public const string QUERY_GET_ALLRESETDATA = "select * from ResetInformation"; // 查询时

        #endregion

        #region 方法

        #region TreeNode 表操作

        /// <summary>
        /// 新增 TreeNode 项目
        /// </summary>
        /// <param name="treeText">设备别名</param>
        /// <param name="treeName">IP</param>
        /// <param name="driverName"></param>
        /// <param name="driverPwd"></param>
        /// <param name="driverPort"></param>
        /// <param name="exceptChannel"></param>
        /// <param name="status">1: 启用 | 0: 未启用</param>
        /// <param name="driverType"></param>
        /// <returns></returns>
        public int AddTreeNodeItem(string treeText, string treeName, string driverName, string driverPwd,
            string driverPort, string exceptChannel, int status, string driverType)
        {
            int resultCount = 0;
            DataSet dataSet = new DataSet();

            try
            {
                OleDbDataAdapter oleDbAdapter = base.GetDataAdapter(QUERY_GET_ALLTREENODEDATA,
                    "db_VWMSConnectionString", string.Format("{0}.exe", Application.ProductName));
                new OleDbCommandBuilder(oleDbAdapter);
                oleDbAdapter.Fill(dataSet, "TreeNode");

                DataRow newRow = dataSet.Tables["TreeNode"].NewRow(); // 添加一个新数据行
                // 添加数据
                newRow["ParentID"] = 1;
                newRow["TreeName"] = treeName;
                newRow["TreeText"] = treeText;
                newRow["DriverName"] = driverName;
                newRow["DriverPwd"] = driverPwd;
                newRow["DriverPort"] = driverPort;
                newRow["ExceptChannel"] = exceptChannel;
                newRow["Status"] = status;
                newRow["DriverType"] = driverType;

                dataSet.Tables["TreeNode"].Rows.Add(newRow);
                resultCount = oleDbAdapter.Update(dataSet, "TreeNode");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, ConstantString.MSG_COMPANY);
            }
            finally
            {
                dataSet.Dispose();
            }

            return resultCount;
        }

        /// <summary>
        /// 修改 TreeNode 项目
        /// </summary>
        /// <param name="id">主键</param>
        /// <param name="treeName">IP</param>
        /// <param name="treeText">设备别名</param>
        /// <param name="driverName"></param>
        /// <param name="driverPwd"></param>
        /// <param name="driverPort"></param>
        /// <param name="exceptChannel"></param>
        /// <param name="status">1: 启用 | 0: 未启用</param>
        /// <param name="driverType"></param>
        /// <returns></returns>
        public int EditTreeNodeItem(string id, string treeText,
            string treeName, string driverName, string driverPwd,
            string driverPort, string exceptChannel, int status, string driverType)
        {
            if (string.IsNullOrWhiteSpace(id))
            {
                MessageBox.Show("ID 不为空！", ConstantString.MSG_COMPANY);
                return 0;
            }

            int resultCount = 0;
            DataSet dataSet = new DataSet();

            try
            {
                OleDbDataAdapter oleDbAdapter = base.GetDataAdapter(string.Format(QUERY_GET_TREENODEDATA_BYID, id),
                    "db_VWMSConnectionString", string.Format("{0}.exe", Application.ProductName));
                new OleDbCommandBuilder(oleDbAdapter);
                oleDbAdapter.Fill(dataSet, "TreeNode");

                if (dataSet.Tables["TreeNode"].Rows.Count <= 0)
                    return resultCount;

                // 修改数据
                //dataSet.Tables["TreeNode"].Rows[0]["ParentID"] = 0;
                dataSet.Tables["TreeNode"].Rows[0]["TreeName"] = treeName;
                dataSet.Tables["TreeNode"].Rows[0]["TreeText"] = treeText;
                dataSet.Tables["TreeNode"].Rows[0]["DriverName"] = driverName;
                dataSet.Tables["TreeNode"].Rows[0]["DriverPwd"] = driverPwd;
                dataSet.Tables["TreeNode"].Rows[0]["DriverPort"] = driverPort;
                dataSet.Tables["TreeNode"].Rows[0]["ExceptChannel"] = exceptChannel;
                dataSet.Tables["TreeNode"].Rows[0]["Status"] = status;
                dataSet.Tables["TreeNode"].Rows[0]["DriverType"] = driverType;

                resultCount = oleDbAdapter.Update(dataSet, "TreeNode");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, ConstantString.MSG_COMPANY);
            }
            finally
            {
                dataSet.Dispose();
            }

            return resultCount;
        }

        /// <summary>
        /// 根据 ID 删除 TreeNode 项目
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns></returns>
        public int DeleteTreeNodeItem(string id)
        {
            if (string.IsNullOrWhiteSpace(id))
            {
                MessageBox.Show("ID 不为空！", ConstantString.MSG_COMPANY);
                return 0;
            }

            try
            {
                string deleteSqlCmd = string.Format(QUERY_DELETE_TREENODE_BYID, id);
                return base.RunSqlCommand(deleteSqlCmd,
                    "db_VWMSConnectionString", string.Format("{0}.exe", Application.ProductName));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, ConstantString.MSG_COMPANY);
                return 0;
            }
        }

        #endregion

        #region SystemInformation 表操作

        /// <summary>
        /// 新增 SystemInformation 项目
        /// </summary>
        /// <param name="machineNum">机器码</param>
        /// <param name="mendTime">补锁时间</param>
        /// <param name="softKeyID">加密锁唯一编号</param>
        /// <param name="trialTimes">试用次数</param>
        /// <param name="token">令牌</param>
        /// <returns></returns>
        public int AddSystemItem(string softKeyID, string machineNum,
            string trialTimes, string token, string mendTime)
        {
            int resultCount = 0;
            DataSet dataSet = new DataSet();

            try
            {
                OleDbDataAdapter oleDbAdapter = base.GetDataAdapter(string.Format(QUERY_GET_ALLSYSTEMDATA_BYID, SYSTEM_GUID),
                    "db_VWMSConnectionString", string.Format("{0}.exe", Application.ProductName));
                new OleDbCommandBuilder(oleDbAdapter);
                oleDbAdapter.Fill(dataSet, "SystemInformation");

                DataRow newRow = dataSet.Tables["SystemInformation"].NewRow(); // 添加一个新数据行
                // 添加数据
                newRow["ID"] = SYSTEM_GUID;
                newRow["SoftKeyID"] = softKeyID;
                newRow["MachineNum"] = machineNum;
                newRow["TrialTimes"] = trialTimes;
                newRow["Token"] = token;
                newRow["MendTime"] = mendTime;

                dataSet.Tables["SystemInformation"].Rows.Add(newRow);
                resultCount = oleDbAdapter.Update(dataSet, "SystemInformation");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, ConstantString.MSG_COMPANY);
            }
            finally
            {
                dataSet.Dispose();
            }

            return resultCount;
        }

        /// <summary>
        /// 修改 SystemInformation 项目
        /// </summary>
        /// <param name="softKeyID">加密锁唯一编号</param>
        /// <param name="machineNum">机器码</param>
        /// <param name="trialTimes">试用次数</param>
        /// <param name="token">令牌</param>
        /// <param name="mendTime">补锁时间</param>
        /// <returns></returns>
        public int EditSystemItem(string softKeyID, string machineNum,
            string trialTimes, string token, string mendTime)
        {
            int resultCount = 0;
            DataSet dataSet = new DataSet();

            try
            {
                OleDbDataAdapter oleDbAdapter = base.GetDataAdapter(string.Format(QUERY_GET_ALLSYSTEMDATA_BYID, SYSTEM_GUID),
                    "db_VWMSConnectionString", string.Format("{0}.exe", Application.ProductName));
                new OleDbCommandBuilder(oleDbAdapter);
                oleDbAdapter.Fill(dataSet, "SystemInformation");

                if (dataSet.Tables["SystemInformation"].Rows.Count <= 0)
                    return resultCount;

                // 修改数据
                dataSet.Tables["SystemInformation"].Rows[0]["SoftKeyID"] = softKeyID;
                dataSet.Tables["SystemInformation"].Rows[0]["MachineNum"] = machineNum;
                dataSet.Tables["SystemInformation"].Rows[0]["TrialTimes"] = trialTimes;
                dataSet.Tables["SystemInformation"].Rows[0]["Token"] = token;
                dataSet.Tables["SystemInformation"].Rows[0]["MendTime"] = mendTime;

                resultCount = oleDbAdapter.Update(dataSet, "SystemInformation");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, ConstantString.MSG_COMPANY);
            }
            finally
            {
                dataSet.Dispose();
            }

            return resultCount;
        }

        /// <summary>
        /// 重置次数
        /// </summary>
        /// <param name="trialTimes">次数</param>
        /// <returns></returns>
        public int ResetTrialTimes(string trialTimes)
        {
            int resultCount = 0;
            DataSet dataSet = new DataSet();

            try
            {
                OleDbDataAdapter oleDbAdapter = base.GetDataAdapter(string.Format(QUERY_GET_ALLSYSTEMDATA_BYID, SYSTEM_GUID),
                    "db_VWMSConnectionString", string.Format("{0}.exe", Application.ProductName));
                new OleDbCommandBuilder(oleDbAdapter);
                oleDbAdapter.Fill(dataSet, "SystemInformation");

                if (dataSet.Tables["SystemInformation"].Rows.Count <= 0)
                    return resultCount;

                // 修改数据
                dataSet.Tables["SystemInformation"].Rows[0]["TrialTimes"] = trialTimes;
                resultCount = oleDbAdapter.Update(dataSet, "SystemInformation");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, ConstantString.MSG_COMPANY);
            }
            finally
            {
                dataSet.Dispose();
            }

            return resultCount;
        }

        /// <summary>
        /// 保存最新数据到 SystemInformation 表中【新增 | 修改（drSystem["ID"] != null）】
        /// </summary>
        /// <param name="drSystem">SystemInformation 表的信息【只含唯一一条记录】</param>
        /// <param name="dataOperation">操作数据库</param>
        public int EditSystemItem(DataRow drSystem,
            SurveillanceDAL dataOperation = null)
        {
            int resultCount = 0;

            if (drSystem == null)
                return resultCount;

            if (dataOperation == null)
                dataOperation = new SurveillanceDAL();

            try
            {
                #region 初始值
                if (drSystem[RegistryOperation.SUBKEYNAME_MACHINENUM] == null ||
                    (drSystem[RegistryOperation.SUBKEYNAME_MACHINENUM] != null &&
                    string.IsNullOrWhiteSpace(drSystem[RegistryOperation.SUBKEYNAME_MACHINENUM].ToString()))) // 机器码
                {
                    if (string.IsNullOrWhiteSpace(Utilities.MachineCode))
                    {
                        #region 生成唯一机器码
                        Utilities.GenerateMachineCode();
                        #endregion
                    }

                    drSystem[RegistryOperation.SUBKEYNAME_MACHINENUM] = Utilities.MachineCode; // 生成唯一自定义机器码
                }

                if (drSystem[RegistryOperation.SUBKEYNAME_TRIALTIMES] == null ||
                    (drSystem[RegistryOperation.SUBKEYNAME_TRIALTIMES] != null &&
                    string.IsNullOrWhiteSpace(drSystem[RegistryOperation.SUBKEYNAME_TRIALTIMES].ToString()))) // 试用次数
                    drSystem[RegistryOperation.SUBKEYNAME_TRIALTIMES] = EncryptAlgorithmHelper.Encrypt2("0", Utilities.MachineCode);

                if (drSystem[RegistryOperation.SUBKEYNAME_TOKEN] == null ||
                    (drSystem[RegistryOperation.SUBKEYNAME_TOKEN] != null &&
                    string.IsNullOrWhiteSpace(drSystem[RegistryOperation.SUBKEYNAME_TOKEN].ToString()))) // 令牌
                    drSystem[RegistryOperation.SUBKEYNAME_TOKEN] = SoftKeyOperation.KEY_EPROM;
                #endregion

                if (drSystem["ID"] != null &&
                    !string.IsNullOrWhiteSpace(drSystem["ID"].ToString())) // 修改
                {
                    resultCount = dataOperation.EditSystemItem(drSystem[RegistryOperation.SUBKEYNAME_SOFTKEYID] != null ? drSystem[RegistryOperation.SUBKEYNAME_SOFTKEYID].ToString() : string.Empty,
                        drSystem[RegistryOperation.SUBKEYNAME_MACHINENUM] != null ? drSystem[RegistryOperation.SUBKEYNAME_MACHINENUM].ToString() : string.Empty,
                        drSystem[RegistryOperation.SUBKEYNAME_TRIALTIMES] != null ? drSystem[RegistryOperation.SUBKEYNAME_TRIALTIMES].ToString() : EncryptAlgorithmHelper.Encrypt2("0", Utilities.MachineCode),
                        drSystem[RegistryOperation.SUBKEYNAME_TOKEN] != null ? drSystem[RegistryOperation.SUBKEYNAME_TOKEN].ToString() : SoftKeyOperation.KEY_EPROM,
                        drSystem[RegistryOperation.SUBKEYNAME_MENDTIME] != null ? drSystem[RegistryOperation.SUBKEYNAME_MENDTIME].ToString() : string.Empty);
                }
                else // 新增
                {
                    resultCount = dataOperation.AddSystemItem(drSystem[RegistryOperation.SUBKEYNAME_SOFTKEYID] != null ? drSystem[RegistryOperation.SUBKEYNAME_SOFTKEYID].ToString() : string.Empty,
                        drSystem[RegistryOperation.SUBKEYNAME_MACHINENUM] != null ? drSystem[RegistryOperation.SUBKEYNAME_MACHINENUM].ToString() : string.Empty,
                        drSystem[RegistryOperation.SUBKEYNAME_TRIALTIMES] != null ? drSystem[RegistryOperation.SUBKEYNAME_TRIALTIMES].ToString() : EncryptAlgorithmHelper.Encrypt2("0", Utilities.MachineCode),
                        drSystem[RegistryOperation.SUBKEYNAME_TOKEN] != null ? drSystem[RegistryOperation.SUBKEYNAME_TOKEN].ToString() : SoftKeyOperation.KEY_EPROM,
                        drSystem[RegistryOperation.SUBKEYNAME_MENDTIME] != null ? drSystem[RegistryOperation.SUBKEYNAME_MENDTIME].ToString() : string.Empty);
                }
            }
            catch (System.Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif
            }

            return resultCount;
        }

        #endregion

        //////////////////////////////////////////////////////////////////////////

        #region UserInformation 表操作

        /// <summary>
        /// 新增 UserInformation 项目
        /// </summary>
        /// <param name="connectionStringName">连接字符串数据库名称</param>
        /// <param name="mainProjectEXE">主工程可执行文件名称</param>
        /// <param name="userName">用户名称信息</param>
        /// <param name="cpuID">CPU 序号</param>
        /// <param name="diskID">磁盘序号</param>
        /// <param name="companyMD5">用户传入的 MD5 值</param>
        /// <param name="projectGUID">项目 ID</param>
        /// <param name="softKeyID">加密锁唯一编号</param>
        /// <param name="machineNum">机器码</param>
        /// <param name="mendTime">补锁时间</param>
        /// <param name="manageTime">办理加密锁时间</param>
        /// <returns></returns>
        public int AddUserItem(string userName,
            string cpuID, string diskID, string companyMD5, string projectGUID, 
            string softKeyID, string machineNum,
            string mendTime, string manageTime)
        {
            int resultCount = 0;
            DataSet dataSet = new DataSet();

            try
            {
                OleDbDataAdapter oleDbAdapter = base.GetDataAdapter(string.Format(QUERY_GET_ALLUSERDATA),
                    "db_VWMSConnectionString", string.Format("{0}.exe", Application.ProductName));
                new OleDbCommandBuilder(oleDbAdapter);
                oleDbAdapter.Fill(dataSet, "UserInformation");

                DataRow newRow = dataSet.Tables["UserInformation"].NewRow(); // 添加一个新数据行
                // 添加数据
                newRow["UserName"] = userName;
                newRow["CPUID"] = cpuID;
                newRow["DiskID"] = diskID;
                newRow["CompanyMD5"] = companyMD5;
                newRow["ProjectGUID"] = projectGUID;
                newRow["SoftKeyID"] = softKeyID;
                newRow["MachineNum"] = machineNum;
                newRow["MendTime"] = mendTime;
                newRow["ManageTime"] = manageTime;

                dataSet.Tables["UserInformation"].Rows.Add(newRow);
                resultCount = oleDbAdapter.Update(dataSet, "UserInformation");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, ConstantString.MSG_COMPANY);
            }
            finally
            {
                dataSet.Dispose();
            }

            return resultCount;
        }

        #endregion

        #region ResetInformation 表操作

        /// <summary>
        /// 新增 ResetInformation 项目
        /// </summary>
        /// <returns></returns>
        public int AddResetItem()
        {
            int resultCount = 0;
            DataSet dataSet = new DataSet();

            try
            {
                OleDbDataAdapter oleDbAdapter = base.GetDataAdapter(string.Format(QUERY_GET_ALLRESETDATA),
                    "db_VWMSConnectionString", string.Format("{0}.exe", Application.ProductName));
                new OleDbCommandBuilder(oleDbAdapter);
                oleDbAdapter.Fill(dataSet, "ResetInformation");

                DataRow newRow = dataSet.Tables["ResetInformation"].NewRow(); // 添加一个新数据行
                // 添加数据
                newRow["ResetTime"] = DateTime.Now;

                dataSet.Tables["ResetInformation"].Rows.Add(newRow);
                resultCount = oleDbAdapter.Update(dataSet, "ResetInformation");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, ConstantString.MSG_COMPANY);
            }
            finally
            {
                dataSet.Dispose();
            }

            return resultCount;
        }

        #endregion

        #endregion
    }
}
